<template>
  <view class="order-page">
    <!-- 顶部导航 -->

    
    <!-- 搜索栏 -->
	<view style="background: #fff;padding-top: 20rpx;">
		<view style="display: flex;align-items: center;padding: 0 25rpx;">
			<view style="display: flex;align-items: center;">
				<u-icon  name="calendar" size="60" color="#666"></u-icon>
			      <uni-datetime-picker
			        type="date"
					placeholder="开始日期"
					class="custom-date-picker"
			        v-model="startDate"
			        @change="onStartDateChange"
			      />
			    </view>
			    <text style="margin: 0 25rpx;">-</text>
			    <view style="display: flex;align-items: center;">
					<u-icon  name="calendar" size="60" color="#666"></u-icon>
			      <uni-datetime-picker
			        type="date"
					placeholder="结束日期"
			        v-model="endDate"
			        @change="onEndDateChange"
			      />
			    </view>
		</view>
		<view class="search-bar">
			
		  <view class="search-input">
		    <u-icon name="search" size="35" color="#999" class="search-icon"></u-icon>
		    <input 
		      type="text" 
		      placeholder="搜索姓名/新手机号/老手机号" 
		      v-model="searchKey"
			  @input="searchOrders"
		      @confirm="searchOrders"
		    />
		  </view>
		  <button class="search-btn" @click="searchOrders">搜索</button>
		  <!-- <button class="search-btn" @click="exportSimpleWord">导出</button> -->
		</view>
	</view>


	<!-- 自定义日期选择器 -->
	
	<view style="padding: 25rpx; background: #f5f7fa;">
		<u-subsection  :list="list" fontSize="26" :current="current" @change="sectionChange"></u-subsection>
	</view>
    <!-- 报单列表 -->
    <view class="order-list">
      <view 
        class="order-item" 
        v-for="(order, index) in orders" 
        :key="order.business_id"
        @click="viewOrderDetail(order.business_id)"
      >
        <!-- 订单头部 -->
        <view class="order-header">
          <text class="order-id">报单号: {{ order.business_id }}</text>
		  <view style="display: flex;align-items: center;">
			  <switch @change="tuiChange(order,$event)" :color="order.status==0?'':'#ff0000'" style="transform:scale(0.7)" :checked="order.status==0?true:false" ></switch>
			  <text class="order-status" :class=" order.status?'status-pending':'status-approved'">{{getStatusText(order.status)  }}</text>
			  <button style="margin-left: 25rpx;" class="action-btn delete-btn" @click.stop="confirmDelete(order.business_id)">
			    <u-icon name="trash" color="#f44336" size="36" class="action-icon"></u-icon>
			  </button>
		  </view>
		  
        </view>
        
        <!-- 订单信息 -->
        <view class="order-info">
          <view class="info-item">
            <text class="info-label">申请人：</text>
            <text class="info-value">{{ order.real_name }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">新手机号：</text>
            <text class="info-value">{{ order.mobile }}</text>
          </view>
		  <view class="info-item">
		    <text class="info-label">旧手机号：</text>
		    <text class="info-value">{{ order.old_mobile }}</text>
		  </view>
          <view class="info-item" v-if="order.type == 0">
            <text class="info-label" >学校名称：</text>
            <text class="info-value">{{ order.school_name }}</text>
          </view>
		  <view class="info-item" v-else>
		    <text class="info-label" >电话卡类型：</text>
		    <text class="info-value">{{ getStatusType(order.type) }}</text>
		  </view>
		  <view class="info-item">
		    <text class="info-label">办理套餐：</text>
		    <text class="info-value">{{ order.package_name }}</text>
		  </view>
		  
          <view class="info-item">
            <text class="info-label">宽带地址：</text>
            <text class="info-value">{{ order.dorm }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">办理时间：</text>
            <text class="info-value">{{ formatDate(order.create_time) }}</text>
          </view>
		  <view class="info-item">
			  <text class="info-label">办理人员：</text>
			  <text class="info-value">{{ order.create_by }}</text>
			</view>
        </view>
        
        <!-- 附件预览 -->
        <view class="attachment-preview" v-if="hasAttachments(order)">
          <view class="preview-title">附件预览</view>
          <view class="attachment-list">
            <view class="attachment-item" v-if="order.idcard_image" @click="previewImage(order.idcard_image)">
              <image :src="order.idcard_image" mode="aspectFill"></image>
              <text>身份证正面</text>
            </view>
            <view class="attachment-item" v-if="order.idcard_image_b" @click="previewImage(order.idcard_image_b)">
              <image :src="order.idcard_image_b" mode="aspectFill"></image>
              <text>身份证反面</text>
            </view>
			<!-- getImageUrl（） -->
            <view class="attachment-item" v-if="order.public_security_code" @click="previewImage(order.public_security_code)">
              <image :src="order.public_security_code" mode="aspectFill"></image>
              <text>公安编码</text>
            </view>
		
			<view class="attachment-item" v-if="order.letter_of_commitment" @click="previewImage(order.letter_of_commitment)">
			  <image :src="order.letter_of_commitment" mode="aspectFill"></image>
			  <text>承诺书</text>
			</view>
			<view class="attachment-item" v-if="order.portrait" @click="previewImage(order.portrait)">
			  <image :src="order.portrait" mode="aspectFill"></image>
			  <text>手持承诺书</text>
			</view>
          </view>
        </view>
        
        <!-- 备注信息 -->
        <view class="remark-section" v-if="order.remark">
          <view class="remark-title">备注信息</view>
          <view class="remark-content">{{ order.remark }}</view>
        </view>
      </view>
      
      <!-- 无数据状态 -->
      <view class="empty-state" v-if="orders.length === 0">
        <text class="empty-text">暂无报单记录</text>
      </view>
    </view>
    
    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore" @click="loadMoreOrders">
      <text>加载更多...</text>
    </view>
  </view>
</template>

<script>
import htmlDocx from 'html-docx-js/dist/html-docx'
export default {
  data() {
    return {
      searchKey: '',
      currentStatus: 'all', // 初始状态为全部
      statusList: ['all', 'pending', 'approved', 'rejected'],
      statusText: {
        'all': '全部',
        'pending': '待审核',
        'approved': '已通过',
        'rejected': '已拒绝'
      },
      orders: [],
      hasMore: false,
      page: 1,
      limit: 10,
      total: 0,
	  current:0,
	  list: ['校园套餐', '大递卡', '骑士卡','会展','逸景'],
	  show:false,
	  selectedDate: '',
	 startDate: '',
	 endDate: '',
	
	// 自定义选择器状态
	showPicker: false,
	pickerType: 'start', // 'start' 或 'end'
	years: [],
	months: [],
	days: [],
		pickerValue: [0, 0, 0],
    }
	ids:''
  },
  
  onLoad(option) {
    this.getmyBusiness(option.id);
	uni.setNavigationBarTitle({
		title:option.username+'报单记录'
	})
	this.ids = option.id
  },
  onReachBottom() {
    if (this.hasMore) {
      this.page++;
      this.getmyBusiness(this.ids);
    }
  },
  methods: {
	onStartDateChange(date) {
	  console.log('开始日期:', date);
	  this.startDate = date
	},
	
	onEndDateChange(date) {
	  console.log('结束日期:', date);
	  this.endDate = date
	},
	  sectionChange(index){
	  	this.current = index
		this.orders = []
		this.getmyBusiness(this.ids)
	  },
	  async  exportSimpleWord(data) {
		let params = {
			start_date:this.startDate,
			end_date:this.endDate,
			type:this.current
		}
		let that = this
		uni.showLoading({ title: '正在生成文档' })
		
	    const res = await this.$api.post('/Business/exportBusinessToWord',params,true)
		if(res.data.code == 200){
			let downloadUrl = res.data.url
			uni.showModal({
				content: res.data.filename+'已导出，请点击下载',
				title:res.data.msg,
				confirmText:'复制链接',
				success: (red) => {
					if(red.confirm){
						that.downloadExcelByUrl(downloadUrl);
					}
				}
			})
			uni.hideLoading()
		} else {
			uni.hideLoading()
		}
		console.log(res,'----')
	  },
	  downloadExcelByUrl(url){
		  uni.downloadFile({
			url:url,
			success: (res) => {
				if(res.statusCode == 200) {
					uni.openDocument({
						filePath:res.tempFilePath,
						fileType:'xlsx',
						success: () => {
							console.log('打开成功')
						}
					})
				}
			}
		})
		  uni.setClipboardData({
			data: url,
			success: function () {
				uni.showToast({
					title: '复制成功',
					icon: 'success'
				});
			},
			fail: function (err) {
				console.error('复制失败:', err);
				uni.showToast({
					title: '复制失败，请重试',
					icon: 'none'
				});
			}
		});
	  },
	  async getmyBusiness(id){
		const params = {
			page:this.page,
			limit:this.limit,
			user_id:id,
			real_name:this.searchKey,
			type:this.current,
			start_date:this.startDate,
			end_date:this.endDate
		}
		const res = await this.$api.post('/user/UserBusiness',params,true)
		if(res.data.code === 200) {
			this.orders = this.orders.concat(res.data.data.list)
			this.total = res.data.data.total
			this.hasMore = this.orders.length < this.total;
		}
	},
   
     
    
    // 加载更多订单
    loadMoreOrders() {
      this.loadOrders();
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 切换筛选状态
    changeStatus(status) {
      this.currentStatus = status;
    },
    getStatusType(status) {
      const statusMap = {
        0: '校园套餐',
        1: '大递卡',
		2:'骑士卡',
		3:'会展大市场',
		4:'逸景大市场'
      };
      return statusMap[status] || '未知状态';
    },
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: '正常',
        1: '退回',
      };
      return statusMap[status] || '未知状态';
    },
    tuiChange(e,event){
		let that = this
		let status = e.status == 0 ?1:0
		console.log('打印',e.status,status)
		uni.showModal({
			content:e.status==0?'是否退回此单？':'是否恢复正常',
			title:'温馨提示',
			success: async (red) => {
				if(red.confirm){
					const res = await that.$api.post('/user/tuidan',{business_id:e.business_id,status:status},true)
					if(res.data.code === 200) {
						this.orders = []
						this.getmyBusiness(this.ids)
					}
				} else {
					this.orders = []
					this.getmyBusiness(this.ids)	
				}
			}
		})
		
	},
    // 获取状态样式类
    getStatusClass(status) {
      const classMap = {
        0: 'status-pending',
        1: 'status-approved',
        2: 'status-rejected'
      };
      return classMap[status] || '';
    },
    // 确认删除
	confirmDelete(id) {
		let that = this
	  uni.showModal({
	  	content:'是否确认删除？',
		title:'温馨提示',
		success: async (red) => {
			if(red.confirm){
				const res = await that.$api.post('/user/del',{business_id:id},true)
				if(res.data.code == 200) {
					this.orders = []
					this.getmyBusiness(this.ids)
				}
			}
		}
	  })
	},
    // 查看订单详情
    viewOrderDetail(orderId) {
      // uni.navigateTo({
      //   url: `/pages/order-detail/index?businessId=${orderId}`
      // });
    },
    
    // 搜索订单
    searchOrders() {
      if (this.searchKey.trim() || this.startDate || this.endDate) {
      
        this.page = 1;
		this.orders = []
        this.getmyBusiness(this.ids);
      }
    },
    
    // 切换筛选面板
    toggleFilter() {
      uni.showToast({
        title: '筛选功能待实现',
        icon: 'none'
      });
    },
    
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '未知时间';
      const date = new Date(dateStr);
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], { hour: '2-digit', minute:'2-digit' });
    },
    
    // 检查是否有附件
    hasAttachments(order) {
      return order.idcard_image_url || order.idcard_image_b_url || order.public_security_code_url;
    },
    
    // 获取图片URL（处理可能的JSON格式）
    getImageUrl(url) {
		let parsed = {}
		try {
		 // 如果是字符串并且以 '/{' 开头，说明是多了一个斜杠
		  if (typeof url === 'string' && url.trim().startsWith('/{')) {
		    url = url.slice(1); // 去掉开头的 '/'
			parsed = JSON.parse(url);
			console.log('imageName---url',parsed)
		  }
		  if (typeof url === 'string' && url.trim().startsWith('{')) {
		    parsed = JSON.parse(url);
			console.log('image---url',parsed.url)
			return parsed.url
		  } else {
		    // 如果不是 JSON，而是直接一个路径，就直接包成对象
		    parsed = {
		      url: url
		    };
			console.log('imageName',parsed)
		  }
		} catch (e) {
		  console.error("图片解析失败", e);
		}
  
    },
    
    // 预览图片
    previewImage(url) {
      const imageUrl = [url];
      if (imageUrl) {
        uni.previewImage({
          current: imageUrl,
          urls: imageUrl
        });
      }
    }
  }
}
</script>

<style scoped>
	.custom-date-container {
	  /* 容器样式，可根据需要调整 */
	  padding: 10rpx 0;
	}
	
	.custom-date-picker ::v-deep .uni-date-editor--x {
	  border: none !important;
	  background-color: transparent !important;
	  padding: 0 !important;
	}
	
	.custom-date-picker ::v-deep .uni-date-editor--x__input {
	  border: none !important;
	  background-color: transparent !important;
	  padding: 0 !important;
	  height: auto !important;
	  min-height: auto !important;
	  line-height: 1.5 !important;
	}
	
	.custom-date-picker ::v-deep .uni-date-editor--x__icon {
	  margin-left: 8rpx !important;
	}
	.action-btn {
	  padding: 0 20rpx;
	    height: 50rpx;
	    line-height: 50rpx;
	    font-size: 24rpx;
	    border-radius: 25rpx;
	    border: none;
	}
	
	.edit-btn {
	  background-color: #e8f3ff;
	  color: #165DFF;
	}
	
	.delete-btn {
	  color: #f44336;
	}
/* 页面基础样式 */
.order-page {
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 导航栏 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 24rpx;
  background: linear-gradient(90deg, #2c82c9, #3a9ee6);
  color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}
.back-btn, .filter-btn {
  font-size: 32rpx;
}
.title {
  font-size: 36rpx;
  font-weight: bold;
}

/* 搜索栏 */
.search-bar {
  display: flex;
  align-items: center;
  padding: 24rpx;
  background-color: #fff;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.search-input {
  flex: 1;
  display: flex;
  align-items: center;
  height: 72rpx;
  background-color: #f5f7fa;
  border-radius: 36rpx;
  padding: 0 24rpx;
}
.search-icon {
  width: 32rpx;
  height: 32rpx;
  margin-right: 16rpx;
}
.search-input input {
  flex: 1;
  height: 72rpx;
  font-size: 28rpx;
  background-color: transparent;
  border: none;
  outline: none;
}
.search-btn {
  width: 160rpx;
  height: 72rpx;
  line-height: 72rpx;
  text-align: center;
  background-color: #007bff;
  color: #fff;
  border-radius: 36rpx;
  margin-left: 24rpx;
  font-size: 28rpx;
  border: none;
  padding: 0;
}

/* 状态标签 */
.status-tabs {
  display: flex;
  background-color: #fff;
  padding: 20rpx 0;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}
.tab-item {
  flex: 1;
  text-align: center;
  font-size: 28rpx;
  padding: 12rpx 0;
  color: #666;
  position: relative;
}
.tab-item.active {
  color: #007bff;
  font-weight: bold;
}
.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 4rpx;
  background-color: #007bff;
  border-radius: 2rpx;
}

/* 报单列表 */
.order-list {
  padding: 0 24rpx;
}
.order-item {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.05);
  overflow: hidden;
}
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  background-color: #f5f7fa;
}
.order-id {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}
.order-status {
  font-size: 24rpx;
  padding: 6rpx 16rpx;
  border-radius: 16rpx;
}
.status-pending {
  background-color: #fff3cd;
  color: #856404;
}
.status-approved {
  background-color: #d4edda;
  color: #155724;
}
.status-rejected {
  background-color: #f8d7da;
  color: #721c24;
}

.order-info {
  padding: 24rpx;
}
.info-item {
  display: flex;
  align-items: center;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}
.info-item:last-child {
  border-bottom: none;
}
.info-label {
  font-size: 26rpx;
  color: #666;
  width: 160rpx;
}
.info-value {
  font-size: 28rpx;
  color: #333;
  flex: 1;
}

.attachment-preview {
  padding: 24rpx;
  border-top: 1rpx solid #f0f0f0;
}
.preview-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
}
.attachment-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}
.attachment-item {
  width: calc(33% - 10.66rpx);
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: #f9f9f9;
  border-radius: 8rpx;
  padding: 12rpx;
  box-sizing: border-box;
}
.attachment-item image {
  width: 100%;
  height: 160rpx;
  border-radius: 8rpx;
  margin-bottom: 8rpx;
}
.attachment-item text {
  font-size: 24rpx;
  color: #666;
}

.remark-section {
  padding: 24rpx;
  border-top: 1rpx solid #f0f0f0;
}
.remark-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
}
.remark-content {
  font-size: 26rpx;
  color: #333;
  line-height: 1.5;
  background-color: #f9f9f9;
  padding: 16rpx;
  border-radius: 8rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}
.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 32rpx;
  opacity: 0.5;
}
.empty-text {
  font-size: 28rpx;
  color: #999;
}

/* 加载更多 */
.load-more {
  text-align: center;
  padding: 32rpx 0;
  font-size: 26rpx;
  color: #999;
  border-radius: 12rpx;
  margin: 24rpx;
  cursor: pointer;
}
</style>